import { ZodError, z } from "zod";
import SuperJSON from "superjson";
import useDeTokenSetCookie from "~/server/utils/handlerDeTokenSetCookie";

const loginSchema = z.object({
  email: z.string().trim().min(3, "邮箱格式错误").email("错误的邮箱格式"),
  password: z.string().min(6, "密码过短").max(20, "密码过长"),
});

export default defineEventHandler(async (event) => {
  const storage = useStorage("data");
  // const storageMDB = useStorage("mongodb");
  // Try to read request body
  const body = await readBody<ReqPayLoad<UserLoginType>>(event).catch(() => {
    throw createError({
      status: 401,
      message: "参数错误",
    });
  });
  console.log("login res body", body);

  try {
    loginSchema.parse(body.data);
  }
  catch (e: any) {
    // console.log("e", e);
    if (e instanceof ZodError) {
      throw createError({
        status: 400,
        data: {
          message: e.errors[0].message,
          code: e.errors[0].code,
          path: e.errors[0].path,
        },
      });
    }
    else {
      throw createError({
        status: 400,
        data: {
          message: "参数错误",
          code: "参数错误",
          path: "",
        },
      });
    }
  }
  const thatUserName = body.data.email.split("@")[0]
  const userHas = await storage.hasItem(
    `users:${thatUserName}`,
  );
  // const userHasMDB = await storageMDB.hasItem(
  //   `users:${thatUserName}`,
  // );
  // if (userHasMDB) {
  //   const thatUser = await storageMDB.getItem<JSONed<ReqPayLoad<UserType>>>(
  //     `users:${thatUserName}`,
  //   );
  //   if (thatUser) {
  //     return thatUser.json;
  //   }
  //   else {
  //     throw createError({
  //       status: 401,
  //       message: "Unauthorized",
  //     });
  //   }
  // }
  // else {
  //   try {
  //     console.log("try set user to MDB");
  //     storageMDB.setItem(`users:${thatUserName}`, 123);
  //     console.log("set user to MDB fin.");
  //   }
  //   catch (e) {
  //     console.error(e);
  //   }
  // }
  if (userHas) {
    const thatUser = await storage.getItem<JSONed<ReqPayLoad<UserType>>>(
      `users:${thatUserName}`,
    );

    if (thatUser) {
      return thatUser.json;
    }
    else {
      throw createError({
        status: 401,
        message: "Unauthorized",
      });
    }
  }
  // ---- new ----
  // console.log(body);
  useDeTokenSetCookie(body.data.email, event);
  console.log("log fin.");
  const userData: ReqPayLoad<UserType> = {
    data: {
      id: 1,
      email: body.data.email,
      phone: "",
      password: "",
      nickname: thatUserName,
      // avatar: "",//暂时砍掉
      sex: "未知",
      desc: "",
      status: 1, // 0 下线 1 启用
      created_time: Date.now(),
      updated_time: Date.now(),
    },
  };
  storage.setItem("user", SuperJSON.stringify(userData));
  return userData;
});
